﻿using Manhua2.Common;
using Manhua2.DataModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Manhua2.Helper;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace Manhua2.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class SearchResultPage : Page
    {
        public SearchResultPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。Parameter
        /// 属性通常用于配置页。</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            string error = null;
            try
            {
                string queryText = e.Parameter as string;
                this.txtQueryText.Text = "\"" + queryText + "\"";

                if (string.IsNullOrEmpty(queryText)) return;

                using (ModelContext context = new ModelContext())
                {
                    this.results.ItemsSource = await context.QueryComicsAsync(queryText);

                    foreach (var item in (ObservableCollection<ComicItem>)this.results.ItemsSource)
                    {
                        if (string.IsNullOrEmpty(item.Cover))
                        {
                            await CoverCacheManager.DownloadCoverAsync(item);
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                error = ex.Message;
            }

            await MethodHelper.ShowMessageDialogNotEmpty(error);
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            if (this.Frame.CanGoBack) this.Frame.GoBack();
            else this.Frame.Navigate(typeof(MainPage));
        }

        private void GridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var comic = e.ClickedItem as ComicItem;
            if (comic != null)
            {
                this.Frame.Navigate(typeof(ComicDirectoryPage), comic.Comic.Id);
            }
        }

        private void btnHome_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage));
        }
    }
}
